<?php

namespace Application\Controllers;

use Application\Services\ArticleService;
use Application\Services\CategoryService;
use Application\Services\ConfigService;
use Application\Services\LinkService;
use Application\Services\MenuService;
use Application\Services\TagService;
use Phalcon\Exception;

class IndexController extends \Phalcon\Mvc\Controller
{
    private $address = ["127.0.0.1", 9090];

    /**
     * @var ArticleService
     */
    private $articleService = null;
    /**
     * @var ConfigService
     */
    private $configService = null;

    /**
     * @var CategoryService
     */
    private $categoryService = null;

    /**
     * @var MenuService
     */
    private $menuService = null;

    /**
     * @var LinkService
     */
    private $linkService = null;

    /**
     * @var TagService
     */
    private $tagService = null;

    private $menus = [];

    private $categorys = [];

    public function initialize()
    {
        $this->articleService = new ArticleService(...$this->address);
        $this->configService = new ConfigService(...$this->address);
        $this->categoryService = new CategoryService(...$this->address);
        $this->menuService = new MenuService(...$this->address);
        $this->linkService = new LinkService(...$this->address);
        $this->tagService = new TagService(...$this->address);
        $this->menus = $this->menuService->GetMenus();
        $this->view->setVar('config', $this->configService->GetConfig());
        $this->view->setVar('site_nav', $this->getNav());
        $this->view->setVar('links', $this->linkService->GetAllLinks());
        $this->view->setVar('tags', $this->tagService->GetAllTags());
    }

    //index/index
    public function indexAction()
    {
        $articles = $this->articleService->GetArticles("1=1", 0, 100);
        $total = $this->articleService->GetArticleTotal("1=1");
        foreach ($articles as $article) {
            try {
                if (!isset($this->categorys[$article->CatId])) {
                    $category = $this->categoryService->GetCategoryInfoById($article->CatId);
                    $this->categorys[$article->CatId] = $category->CatName;
                } else {
                    $category = $this->categorys[$article->CatId];
                }
                $article->CatName = $category->CatName;
                continue;
            } catch (Exception $exception) {
                continue;
            }
        }
        $this->view->setVar("articles", $articles);
        $this->view->setVar("total", $total);
    }

    public function listAction()
    {

    }

    public function articleAction()
    {
        $id = $this->request->get("id");
        $id = intval($id);
        if ($id < 1) {
            return $this->response->setContent("Id错误");
        }
        $article = $this->articleService->GetArticleById($id);
        if (!$article) {
            return $this->response->setContent("没有文章内容");
        }
        $category = $this->categoryService->GetCategoryInfoById($article->CatId);
        $article->CatName = $category ? $category->CatName : "";
        $this->view->setVar('article', $article);
        $article_tags = $this->tagService->GetTagsByArticleId($article->Id);
        $this->view->setVar('article_tags', $article_tags);
    }

    /**
     * 取得Nav的HTML结构
     */
    private function getNav()
    {
        $categorys = $this->menus;
        $nav = '<ul class="am-nav am-nav-pills am-topbar-nav"><li><a href="/">首页</a></li>';
        if ($categorys) {
            $top = [];  //最顶层目录
            $treeNav = [];
            foreach ($categorys as $parent) {
                $parent->ParentId == 0 ? $top[] = $parent : false;
            }
            foreach ($top as $item) {
                $treeNav[$item->Id] = [];
                $treeNav[$item->Id]['data'] = $item;
                $treeNav[$item->Id]['next'] = [];
                foreach ($categorys as $category) {
                    if ($category->ParentId == $item->Id) {
                        $treeNav[$item->Id]['next'][] = $category;
                    }
                }
            }
            foreach ($treeNav as $id => $category) {
                if (count($category['next'])) {
                    $nav .= '<li class="am-dropdown" data-am-dropdown>';
                    $nav .= '<a class="am-dropdown-toggle" data-am-dropdown-toggle href="javascript:;">';
                    $nav .= $category['data']->NavName;
                    $nav .= '<span class="am-icon-caret-down"></span></a><ul class="am-dropdown-content">';
                    foreach ($category['next'] as $item) {
                        $nav .= '<li><a href="' . $this->getUrl($item->Url, $item->Id) . '">' . $item->NavName . '</a></li>';
                    }
                    $nav .= '</ul>';
                } else {
                    $nav .= '<li><a href="' . $this->getUrl($category['data']->Url, $category['data']->Id) . '">' . $category['data']->NavName . '</a></li>';
                }
            }

        }
        $nav .= "</ul>";
        return $nav;
    }


    private function getUrl($url, $cid)
    {
        if (strpos($url, '/list') !== false) {
            return $this->url->get('/index/list', ['id' => $cid]);
        }
        return $url;
    }

    private function getPagerHtml()
    {
    }

    public function __destruct()
    {
        $this->categoryService->close();
        $this->menuService->close();
        $this->configService->close();
        $this->articleService->close();
        $this->linkService->close();
        $this->tagService->close();
    }
}